
package com.xifan.myaccount.fragments;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;

import com.xifan.myaccount.R;
import com.xifan.myaccount.database.DatabaseImpl;
import com.xifan.myaccount.entity.Account;
import com.xifan.myaccount.util.SmartType;
import com.xifan.myaccount.util.UiHelper;
import com.xifan.myaccount.widget.MoneyView;

import java.util.HashMap;
import java.util.List;

public class AccountManage extends PreferenceFragment implements OnPreferenceChangeListener {

    private ListPreference mAccountPref;
    private Preference mAddAccount;
    private PreferenceCategory mEditCategory;
    private EditText mAddAccountName;
    private MoneyView mAccountMoney;
    private PopupWindow mNumberpad;
    private Spinner mAccountTypeSpinner;
    private View mAddAccountView;

    private List<String> mAccountTypeList;

    private Context mContext;
    private LoadTask mTask;

    private int mCurrentAccount;

    private static final String KEY_DEFAULT_ACCOUNT = "default_account";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preference_manage_account);

        mContext = getActivity();
        mTask = new LoadTask();
        getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
        init();
    }

    private void init() {
        mEditCategory = (PreferenceCategory) findPreference("edit_category");
        mAccountPref = (ListPreference) findPreference("current_account");
        mAddAccount = (Preference) findPreference("add_account");
        mTask.execute();
    }

    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
        String key = preference.getKey();
        if (key == mAddAccount.getKey()) {
            mAddAccountView = View.inflate(mContext, R.layout.view_dialog_add_account, null);
            mAddAccountName = (EditText) mAddAccountView.findViewById(R.id.add_account_name);
            mAccountMoney = (MoneyView) mAddAccountView.findViewById(R.id.add_account_money);
            mAccountTypeSpinner = (Spinner) mAddAccountView
                    .findViewById(R.id.add_account_type_spinner);
            mAccountTypeSpinner.setAdapter(new ArrayAdapter<String>(mContext,
                    R.layout.type_spinner_view, mAccountTypeList));
            AlertDialog dialog = UiHelper.createViewDialog(mContext,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == Dialog.BUTTON_POSITIVE) {
                                createAccount();
                            }
                        }
                    }, mAddAccountView,
                    getString(R.string.pref_account_manage_add_account));
            mAccountMoney.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if (mNumberpad == null)
                        mNumberpad = UiHelper.createNumberPadWindow(mContext, mAccountMoney);
                    if (!mNumberpad.isShowing())
                        mNumberpad.showAtLocation(getView(), Gravity.BOTTOM, 0, 0);
                    else
                        mNumberpad.dismiss();
                }
            });
            dialog.show();
        } else if (key.equals(KEY_DEFAULT_ACCOUNT)) {
            Toast.makeText(mContext, R.string.pref_account_manage_default_account,
                    Toast.LENGTH_SHORT).show();
        }
        return super.onPreferenceTreeClick(preferenceScreen, preference);
    }

    private void createAccount() {
        DatabaseImpl db = new DatabaseImpl(mContext);
        ContentValues cv = new ContentValues();
        cv.put("total", Float.parseFloat(mAccountMoney.getText()));
        cv.put("revenue", 0);
        cv.put("expend", 0);
        cv.put("accountType", mAccountTypeSpinner.getSelectedItemPosition() + 1);
        if (TextUtils.isEmpty(mAddAccountName.getText().toString()))
            cv.put("accountName", mAccountTypeSpinner.getSelectedItem().toString());
        else
            cv.put("accountName", mAddAccountName.getText().toString());
        long row = db.doInsert("account", cv);
        Toast.makeText(mContext,
                row > -1 ? R.string.msg_add_account_success : R.string.msg_add_account_failed,
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        if (preference == mAccountPref) {
            mCurrentAccount = Integer.parseInt(newValue.toString());
            SharedPreferences prefs = mContext.getSharedPreferences("pref", 0);
            prefs.edit().putInt("currentAccount", mCurrentAccount).apply();
            getActivity().setResult(-1);
        }
        return false;
    }

    public class LoadTask extends AsyncTask<Void, Void, HashMap<String, Object>> {

        @Override
        protected HashMap<String, Object> doInBackground(Void... params) {
            SharedPreferences prefs = mContext.getSharedPreferences("pref", 0);
            mCurrentAccount = prefs.getInt("currentAccount", Account.DEFAULT_ACCOUNT_ID);
            mAccountTypeList = SmartType.getAccountTypeList();
            List<Account> mAccountList = SmartType.getAccountList();

            String[] entries = new String[mAccountList.size()];
            String[] entryValues = new String[mAccountList.size()];

            int currentIndex = 0;
            for (int i = 0, s = mAccountList.size(); i < s; i++) {
                String tmpName = mAccountList.get(i).getAccountName();
                entries[i] = TextUtils.isEmpty(tmpName) ? mAccountTypeList.get(mAccountList.get(i)
                        .getAccountType()) : tmpName;
                if (mAccountList.get(i).getId() == mCurrentAccount)
                    currentIndex = i;
                entryValues[i] = String.valueOf(i);
            }

            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("Entries", entries);
            map.put("Values", entryValues);
            map.put("Index", currentIndex);
            map.put("List", mAccountList);
            return map;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void onPostExecute(HashMap<String, Object> result) {
            super.onPostExecute(result);
            mAccountPref.setEntries((String[]) result.get("Entries"));
            mAccountPref.setEntryValues((String[]) result.get("Values"));
            mAccountPref.setValueIndex((Integer) result.get("Index"));
            mAccountPref.setOnPreferenceChangeListener(AccountManage.this);
            List<Account> accountList = (List<Account>) result.get("List");

            int counter = 1;
            for (Account ac : accountList) {
                if (ac.getId() == 1) {
                    // Default cash account
                    Preference newPref = new Preference(mContext);
                    newPref.setTitle(TextUtils.isEmpty(ac.getAccountName()) ? mAccountTypeList
                            .get(0) : ac.getAccountName());
                    newPref.setKey(KEY_DEFAULT_ACCOUNT);
                    newPref.setSummary(getResources().getString(
                            R.string.pref_account_manage_detail_balance, mAccountTypeList
                                    .get(ac.getAccountType()), ac.getTotal()));
                    mEditCategory.addPreference(newPref);
                    newPref.setOrder(0);
                } else {
                    CheckBoxPreference newPref = new CheckBoxPreference(mContext);
                    newPref.setKey("extraAccount" + counter);
                    newPref.setSummary(getResources().getString(
                            R.string.pref_account_manage_detail_balance, mAccountTypeList
                                    .get(ac.getAccountType()), ac.getTotal()));
                    newPref.setChecked(true);
                    newPref.setTitle(TextUtils.isEmpty(ac.getAccountName()) ? mAccountTypeList
                            .get(ac.getAccountType()) : ac.getAccountName());
                    mEditCategory.addPreference(newPref);
                }
            }
        }

    }

    @Override
    public void onPause() {
        mTask.cancel(true);
        super.onPause();
    }

}
